package com.power.manager;

import com.power.mapper.TClueMapper;
import com.power.mapper.TCustomerMapper;
import com.power.model.TClue;
import com.power.model.TCustomer;
import com.power.model.TUser;
import com.power.query.CustomerQuery;
import com.power.util.LoginInfoUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class CustomerManager {
    @Resource
    private TCustomerMapper tCustomerMapper;
    @Resource
    private TClueMapper tClueMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean addCustomer(CustomerQuery customerQuery) {
        int clueState = tClueMapper.selectClueStateById(customerQuery.getClueId());
        if (clueState == -1) {
            throw new RuntimeException("该线索已经转过客户了，不能重复转客户");
        }
        TCustomer tCustomer = new TCustomer();
        BeanUtils.copyProperties(customerQuery, tCustomer);
        TUser tUser = LoginInfoUtil.getUserFromToken(customerQuery.getToken());
        tCustomer.setCreateBy(tUser.getId());
        tCustomer.setCreateTime(new Date());
        int addCount = tCustomerMapper.insertSelective(tCustomer);
        TClue tClue = new TClue();
        tClue.setId(customerQuery.getClueId());
        tClue.setState(-1);
        int updateCount = tClueMapper.updateByPrimaryKeySelective(tClue);
        return addCount + updateCount == 2;
    }
}
